import React from 'react'
import * as PropTypes from 'prop-types';
import {FormFieldStore} from "../Form";
import {StoreManager} from "@/stores";

export class InputBase extends React.Component {
    static contextTypes = {
        formSettings: PropTypes.object
    }
    static propTypes = {
        id: PropTypes.string,
        name: PropTypes.string.isRequired,
        value: PropTypes.string,
        readOnly: PropTypes.bool,
        disabled: PropTypes.bool,
        validations: PropTypes.arrayOf(PropTypes.func)
    }
    static defaultProps = {
        value: '',
        type: 'text',
        validations: [],
        showErrors: true
    }

    constructor(props, context) {
        super(props, context)
        const parent = context.formSettings && context.formSettings.store
        this.store = StoreManager.create(new FormFieldStore(props), parent)

        this.formSettings = this.context.formSettings
    }

    componentWillUnmount() {
        StoreManager.delete(this.store)
    }

    onChange = (e) => {
        if (this.props.onChange) {
            this.props.onChange(e)
        }
        this.store.changeValue(e.target.value)
        if (this.formSettings.showErrorsOnChange) {
            this.store.validate()
        }
    }
    onKeyDown = (e) => {

    }

    onBlur = (e) => {
        if (this.formSettings.showErrorsOnBlur) {
            this.store.validate()
        }
    }
}
